// onload
$(document).ready(function() {
	deviceTree.list();
});

var ENTER_KEY = "13";
var deviceId;

var deviceTree = {
	deviceTreeUrl : contextPath + "/device"
	// 노드 목록 조회
	,list : function() {
		var request = $.ajax({
			url : this.deviceTreeUrl
			,type : "GET"
			,dataType : "json"
		});
		request.done(function(list) {
			var html = [];
			var count = list.length;
			var imageIcon = [
					contextPath + "/resources/images/tree/root.png", 
					];
			
			for ( var i = 0; i < count; i++ ) {
				data = list[i];
				html.push({ 
					"id" 		: data["id"],
					"parent" 	: "#",
					"text" 		: data["name"],
					"icon" 		: imageIcon[0],
					"state" 	: { "opened" : true }
				});
			}
			$("#deviceTree").jstree({
				"core" : {
					"data" 				: html,
					"check_callback" 	: true
				},
				"plugins" : [ "contextmenu", "search", "crrm" ],
				// 마우스 우측 클릭 메뉴
				"contextmenu" : {					
					"items" : {
						"create" : {
							"separator_before" : false,
							"separator_after"  : true,
							"label"            : "등록",
							"action"           : 
												function() {
													var url 			= contextPath + "/device/addDevice";
													var screenWidth 	= screen.availWidth;
													var screenHeight 	= screen.availHeight;
													var popupWidth		= 370;
													var popupHeight		= 500;
													var xpos			= (screenWidth - popupWidth)/2;
													var ypos			= (screenHeight - popupHeight)/2;
													var options 		= "width=" + popupWidth + ", height=" + popupHeight + 
													", top=" + ypos + ", left=" + xpos + 
													", resizable=no, scrollbars=no, alwaysReised=yes, location=no";
													
													window.open(url, "", options);
												}
						},
						"update" : {
							"separator_before" : false,
							"separator_after"  : true,
							"label"            : "수정",
							"action"           : 
												function() {
													var updateDeviceWindow	= null;
													var url					= contextPath + "/device/updateDevice";
													var screenWidth 		= screen.availWidth;
													var screenHeight 		= screen.availHeight;
													var popupWidth			= 370;
													var popupHeight			= 500;
													var xpos				= (screenWidth - popupWidth)/2;
													var ypos				= (screenHeight - popupHeight)/2;
													var options 			= "width=" + popupWidth + ", height=" + popupHeight + 
													", top=" + ypos + ", left=" + xpos + 
													", resizable=no, scrollbars=no, alwaysReised=no, location=no";
													
													updateDeviceWindow = window.open(url, "", options);
													updateDeviceWindow.focus();
													
													if ( updateDeviceWindow != null ) {
														updateDeviceWindow.oneDeviceData(deviceId);
													}
												}
						},
						"remove" : {
							"separator_before" : false,
							"separator_after"  : true,
							"label"            : "삭제",
							"action"           : function() { deviceTree.del(deviceId); }
						},
						"info" : {
							"separator_before" : false,
							"separator_after"  : true,
							"label"            : "DEVICE 정보",
							"action"           : function() { EventBus.dispatch(EventType.ALARM_RECEIVED, null, deviceId); }
						}
					}
				}
			});
			// 마우스 이벤트가 발생한 Device의 Id값 추출
			$("#deviceTree").on("changed.jstree", function (e, data) {
			    var i, j, r = [];
			    
			    for ( i = 0, j = data.selected.length; i < j; i++ ) {
			      r.push(data.instance.get_node(data.selected[i]).id);
			    }
			    
			    deviceId = r.join(", ");
			  }).jstree();
			// 검색 이벤트
			$("#searchButton").click(function() {
				if ( $("#searchNode").val() ) {
					$("#deviceTree").jstree("search", $("#searchNode").val());
				}
				else {
					$("#deviceTree").jstree("clear_search");
				}
			});
			$("#searchNode").keydown(function(e) {
				if ( e.keyCode == ENTER_KEY ) {
					$("#deviceTree").jstree("search", $("#searchNode").val());
				}
			});
		});
		request.fail(function(jqXHR, textStatus) {
			alert("Request failed: " + textStatus);
		});
	}
	//데이터 삭제
	,del : function(deviceId) {
		if(confirm('삭제하시겠습니까?')) {
			var request = $.ajax({
				url : this.deviceTreeUrl + '/' + deviceId
				,type : 'DELETE'
				,dataType : 'json'
			});
			request.done(function() {
				//deviceTree.list();
				//현재창 refresh
				refreshTree();
				//location.reload();
			});
			request.fail(function(jqXHR, textStatus) {
				alert('Request failed: ' + textStatus);
			});
		}
	}
};

function refreshTree() {
	alert("refreshTree 호출");
	
	$("#deviceTree").jstree("refresh");
	$("#deviceTree").jstree("deselect_all");
}